
using Backoffice.Application.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Backoffice.Application.DTOs;
using BackOffice.Application.DTOs;
using Backoffice.Domain.Entities.App;
using UniversalAdmin.Shared.Extensions;
using BackOffice.Application.Services;
using BackOffice.Application.Common;
using BackOffice.Application.Services;
using BackOffice.Application.Common;

namespace Backoffice.Api.Controllers;
[ApiController]
[Route("api/[controller]")]
[Authorize]
public class UserController : ControllerBase
{
    private readonly UserService _userService;
    private readonly IUserRepository _userRepo;
    private readonly ILogService _logService;

    public UserController(UserService userService, IUserRepository userRepo, ILogService logService)
    {
        _userService = userService;
        _userRepo = userRepo;
        _logService = logService;
    }
   

    [HttpGet("profile")]
    public async Task<IActionResult> GetProfile()
    {
        try
        {
            var user = await _userService.GetCurrentUserAsync();
            if (user == null)
            {
                await LogHelper.LogWarningAsync(_logService, HttpContext, "获取用户资料失败", "用户未找到");
                return NotFound("用户未找到");
            }

            await LogHelper.LogInfoAsync(_logService, HttpContext, "获取用户资料", $"获取用户资料: {user.Username}");
            return Ok(new UserDto(user.Username, user.Email, user.Phone));
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "获取用户资料异常", $"获取用户资料异常: {ex.Message}");
            throw;
        }
    }

    [HttpPut("profile")]
    public async Task<IActionResult> UpdateProfile([FromBody] UserDto dto)
    {
        try
        {
            await _userService.UpdateUserInfoAsync(dto);
            await LogHelper.LogInfoAsync(_logService, HttpContext, "更新用户资料", $"更新用户资料: {dto.Name}");
            return Ok("更新成功");
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "更新用户资料异常", $"更新用户资料异常: {dto.Name} - {ex.Message}");
            return BadRequest(ex.Message);
        }
    }

    [HttpPut("password")]
    public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordDto dto)
    {
        try
        {
            if (dto.NewPassword != dto.ConfirmPassword)
            {
                await LogHelper.LogWarningAsync(_logService, HttpContext, "修改密码失败", "新密码和确认密码不一致");
                return BadRequest("新密码和确认密码不一致");
            }
                
            await _userService.ChangePasswordAsync(dto.CurrentPassword, dto.NewPassword);
            await LogHelper.LogInfoAsync(_logService, HttpContext, "修改密码", "密码修改成功");
            return Ok("密码更新成功");
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "修改密码异常", $"修改密码异常: {ex.Message}");
            return BadRequest(ex.Message);
        }
    }

    [HttpPost("roles")]
    public async Task<IActionResult> AssignRole([FromBody] AssignRoleDto dto)
    {
        try
        {
            var role = new AppRole(dto.Name, "角色描述");
            await _userService.AssignRoleAsync(role);
            await LogHelper.LogInfoAsync(_logService, HttpContext, "分配角色", $"分配角色: {dto.Name}");
            return Ok("角色分配成功");
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "分配角色异常", $"分配角色异常: {dto.Name} - {ex.Message}");
            return BadRequest(ex.Message);
        }
    }

    [HttpDelete("roles/{roleId}")]
    public async Task<IActionResult> RemoveRole(Guid roleId)
    {
        try
        {
            await _userService.RemoveRoleAsync(roleId);
            await LogHelper.LogInfoAsync(_logService, HttpContext, "移除角色", $"移除角色: {roleId}");
            return Ok("角色移除成功");
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "移除角色异常", $"移除角色异常: {roleId} - {ex.Message}");
            return BadRequest(ex.Message);
        }
    }

    ///用户接口
    [HttpGet("tree")]
    public async Task<IActionResult> GetUserTree()
    {
        try
        {
            var users = await _userService.GetUserTreeAsync();
            await LogHelper.LogInfoAsync(_logService, HttpContext, "获取用户树", "获取用户树成功");
            return Ok(users);
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "获取用户树异常", $"获取用户树异常: {ex.Message}");
            return BadRequest(ex.Message);
        }
    }

    [HttpGet]
    public async Task<IActionResult> GetUsers(
        [FromQuery] string? keyword,
        [FromQuery] int page = 1,
        [FromQuery] int size = 10,
        CancellationToken ct = default)
    {
        try
        {
            var paged = await _userRepo.GetUsersPagedAsync(keyword, page, size, ct);
            await LogHelper.LogInfoAsync(_logService, HttpContext, "获取用户列表", $"获取用户列表: 关键词={keyword ?? "全部"}, 页码={page}, 大小={size}");
            return Ok(paged);
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "获取用户列表异常", $"获取用户列表异常: {ex.Message}");
            throw;
        }
    }

    // 创建用户
    [HttpPost("create")]
    public async Task<IActionResult> CreateUser([FromBody] CreateUserDto dto)
    {
        try
        {
            var user = await _userService.CreateUserAsync(dto);
            await LogHelper.LogInfoAsync(_logService, HttpContext, "创建用户", $"创建用户: {dto.Username}");
            return Ok(new { message = "用户创建成功", user });
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "创建用户异常", $"创建用户异常: {dto.Username} - {ex.Message}");
            return BadRequest(ex.Message);
        }
    }

    // 更新用户
    [HttpPut("update")]
    public async Task<IActionResult> UpdateUser([FromBody] UpdateUserDto dto)
    {
        try
        {
            var user = await _userService.UpdateUserAsync(dto);
            await LogHelper.LogInfoAsync(_logService, HttpContext, "更新用户", $"更新用户: {dto.Username}");
            return Ok(new { message = "用户更新成功", user });
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "更新用户异常", $"更新用户异常: {dto.Username} - {ex.Message}");
            return BadRequest(ex.Message);
        }
    }

    // 删除用户
    [HttpDelete("delete/{userId}")]
    public async Task<IActionResult> DeleteUser(Guid userId)
    {
        try
        {
            await _userService.DeleteUserAsync(userId);
            await LogHelper.LogInfoAsync(_logService, HttpContext, "删除用户", $"删除用户: {userId}");
            return Ok(new { message = "用户删除成功" });
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "删除用户异常", $"删除用户异常: {userId} - {ex.Message}");
            return BadRequest(ex.Message);
        }
    }

    // 根据ID获取用户详情
    [HttpGet("detail/{userId}")]
    public async Task<IActionResult> GetUserDetail(Guid userId)
    {
        try
        {
            var user = await _userService.GetUserByIdAsync(userId);
            if (user == null)
            {
                await LogHelper.LogWarningAsync(_logService, HttpContext, "获取用户详情失败", $"用户未找到: {userId}");
                return NotFound("用户未找到");
            }

            await LogHelper.LogInfoAsync(_logService, HttpContext, "获取用户详情", $"获取用户详情: {user.Username}");
            return Ok(user);
        }
        catch (Exception ex)
        {
            await LogHelper.LogErrorAsync(_logService, HttpContext, "获取用户详情异常", $"获取用户详情异常: {userId} - {ex.Message}");
            return BadRequest(ex.Message);
        }
    }
}